<template>
  <view
    :class="['top-safety', titleClass]"
    :style="{
      /*  minHeight: `${height}px`, */
      minHeight: `10vh`,
      width: '100%',
      height: `10vh`,
      backgroundColor: props.bgColor,
    }"
  >
    <view class="top-safety-title flex align-items">
      <slot name="title">
        <u-icon
          @click="backPage"
          v-if="config.showBack"
          size="18rpx"
          :color="props.color"
          name="arrow-left"
          custom-class="title-icon"
          hover-class="title-icon--hover"
        ></u-icon>
        <text :style="{ color: props.color }" class="title-text">{{ config.title }}</text>
      </slot>
    </view>
    <view class="top-safety-content">
      <slot>
        <view></view>
      </slot>
    </view>
    <view class="top-safety-btns" :style="{ bottom: wxClientRect.bottom }">
      <slot name="btns">
        <view class="btns-item hide-icon loading" v-if="config.isAppBackendDownload">
          <u-icon custom-prefix="iconzhucan" name="gengxin" :size="iconStyle.size" :color="iconStyle.color"></u-icon>
        </view>
        <view class="btns-item hide-icon" v-if="config.isFaceSyncRuning">
          <u-icon
            custom-prefix="iconzhucan"
            name="clouddownload"
            :size="iconStyle.size"
            :color="iconStyle.color"
          ></u-icon>
        </view>
        <view class="btns-item" v-if="!isHomePage">
          <u-icon
            custom-prefix="iconzhucan"
            name="houtaishangpinguanli"
            :size="iconStyle.size"
            :color="iconStyle.color"
            @click="toHomePage"
          ></u-icon>
        </view>
        <view class="btns-item" @click="openWifiSetting">
          <u-icon
            v-if="config.isConnected"
            custom-prefix="iconzhucan"
            name="wifi1"
            :size="iconStyle.size"
            :color="iconStyle.color"
          ></u-icon>
          <u-icon
            v-else
            custom-prefix="iconzhucan"
            name="wifioff"
            :size="iconStyle.size"
            :color="iconStyle.color"
          ></u-icon>
        </view>
        <view class="btns-item">
          <u-icon
            @click="toPrinterPage"
            custom-prefix="iconzhucan"
            :name="isPrinterNormal ? 'printer' : 'printeralert'"
            :size="iconStyle.size"
            :color="iconStyle.color"
          ></u-icon>
        </view>
        <view class="btns-item">
          <u-icon custom-prefix="iconzhucan" name="bell" :size="iconStyle.size" :color="iconStyle.color"></u-icon>
        </view>
        <view class="btns-item">
          <u-icon
            custom-prefix="iconzhucan"
            name="wode"
            :size="iconStyle.size"
            :color="iconStyle.color"
            @click="toUserPage"
          ></u-icon>
        </view>
      </slot>
    </view>
    <view class="fixed-version">{{ version }}</view>
  </view>
</template>
<script setup lang="ts">
import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import { ref, onMounted, reactive, computed, watch, onBeforeUnmount } from "vue";
import { useStore } from "vuex";
import appConfig from "@/common/config";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  titleClass: {
    type: String,
    default: "",
  },
  color: {
    type: String,
    default: "white",
  },
  bgColor: {
    type: String,
    default: "transparent",
  },
  showBack: {
    type: Boolean,
    default: false,
  },
});

const config = reactive({
  title: props.title,
  showBack: props.showBack,
  isConnected: true,
  networkType: "wifi",
  isFaceSyncRuning: false,
  isAppBackendDownload: false,
});

// 监听 props 变化
watch(props, (newVal) => {
  console.log("newVal", newVal);
  config.title = newVal.title;
  config.showBack = newVal.showBack;
});

const version = ref(appConfig.VERSION);

// 整体组件高度
const height = ref(44);
// 状态栏高度
const statusBarHeight = ref(18);
// 小程序胶囊
const wxClientRect: UniNamespace.GetMenuButtonBoundingClientRectRes = reactive({
  bottom: 0,
  height: 0,
  left: 0,
  right: 0,
  top: 0,
  width: 0,
});

//
const showdowLenght = ref("0em");
onMounted(async () => {
  // 获取状态栏高度
  const sys = uni.getSystemInfoSync();
  statusBarHeight.value = Number(sys.statusBarHeight);
  // height.value = statusBarHeight.value;

  // #ifdef MP-WEIXIN
  // 小程序右上角胶囊位置信息（用于一些自定义导航条布局）
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect();

  height.value = statusBarHeight.value + menuButtonInfo.height;
  // #endif

  // #ifdef APP
  // 加上状态栏高度
  height.value = statusBarHeight.value + 40;
  // #endif

  showdowLenght.value = props.title.length + "em";

  // 获取 网络状态
  // 查询当前网络状态
  uni.getNetworkType({
    success: (res) => {
      // console.log("当前网络类型:", res.networkType);
      // console.log("是否连接网络:", res.isConnected ? "是" : "否");
      config.isConnected = res.networkType == "wifi" ? true : res.isConnected;
      config.networkType = res.networkType;
    },
    fail: (err) => {
      console.error("获取网络状态失败:", err);
    },
  });

  // // 监听网络状态变化
  // uni.onNetworkStatusChange((res) => {
  //   console.log("网络类型变化:", res.networkType);
  //   console.log("连接网络状态变化:", res.isConnected ? "已连接" : "断开连接");
  //   config.isConnected = res.isConnected;
  //   config.networkType = res.networkType;
  // });

  // 获取打印机状态

  // 获取通知

  // 监听后台人脸数据同步情况
  uni.$on("signFaceProcess", ({ status }) => {
    config.isFaceSyncRuning = status == "start" ? true : false;
  });

  // 监听APP后台下载更新状况
  uni.$on("app:backend-download", ({ status }) => {
    config.isAppBackendDownload = status == "start" ? true : false;
  });
});

onBeforeUnmount(() => {
  uni.$off("signFaceProcess");
  uni.$off("app:backend-download");
});

const iconStyle = {
  color: props.color || "white",
  size: "18rpx",
  weight: "bold",
};

const backPage = () => {
  uni.navigateBack({
    delta: 1,
  });
};

// 判断当前页是否首页
const isHomePage = computed(() => {
  const homePage = import.meta.env.VITE_PAGE_HOME;
  const currPage = getCurrentPages()[getCurrentPages().length - 1]?.$page?.fullPath;
  return currPage === homePage;
});

const toHomePage = () => {
  uni.reLaunch({
    url: import.meta.env.VITE_PAGE_HOME,
  });
};

const store = useStore();

// 打印机是否正常
const isPrinterNormal = computed(() => {
  return store.getters.usbPrinterStatus;
});

// 跳转设备页
const toPrinterPage = () => {
  uni.navigateTo({
    url: "/pages/subSetting/device-connect/device-connect",
  });
};

// 跳转我的
const toUserPage = () => {
  const userPage = "/pages/subHome/user/index";
  const currPage = getCurrentPages()[getCurrentPages().length - 1]?.$page?.fullPath;
  if (userPage == currPage) return;
  uni.navigateTo({
    url: userPage,
  });
};

// 跳转wifi设置
const openWifiSetting = async () => {
  await asyncExecFunction("HnXfjWifiSetting");
};
</script>
<style lang="scss" scoped>
.top-safety {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  width: 100%;
  overflow: hidden;
  font-weight: bold;
  transition: all 0.3s;
  padding: 10rpx;
  font-size: 20rpx;
  box-sizing: border-box;
  // 悬停顶部
  position: sticky;
  top: 0;
  z-index: 99;

  &-title {
    font-size: 16rpx;
    .title-icon {
      padding: 10rpx 0;
    }
    .title-icon--hover {
      // 字体影子
      text-shadow: 2px 2px 6px white;
    }
    .title-text {
      font-size: 14rpx;
      margin-left: 10rpx;
      display: flex;
      align-items: center;
    }
  }

  &-content {
    flex: auto;
  }

  &-btns {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;

    .btns-item {
      padding: 0rpx 8rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.loading {
  // 加载无限旋转动画
  animation: rotate 3s linear infinite;
}

.hide-icon {
  opacity: 0.3;
  padding: 0 !important;
  margin: 0rpx 8rpx;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.fixed-version {
  position: fixed;
  bottom: 0.3125rem;
  right: 0.3125rem;
  opacity: 0.1;
  font-size: 15px;
  font-weight: lighter;
  // 不接收点击事件
  pointer-events: none;
}
</style>
